/*

  The contents of this file are subject to the Mozilla Public License Version
  1.1 (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at 
  
           http://www.mozilla.org/MPL/ 
  
  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  for the specific language governing rights and limitations under the License. 
  
  The Original Code is KazeOS Framework.
  
  The Initial Developer of the Original Code is
  ALCARAZ Marc (aka eKameleon) <ekameleon@gmail.com>.
  Portions created by the Initial Developer are Copyright (C) 2004-2010
  the Initial Developer. All Rights Reserved.
  
  Contributor(s) :
  
*/

/**
 * @requires 
 */
load( "src/evisio/vo/UserVO.asc" ) ;
load( "src/system/Arrays.asc" ) ;

load( "config.asc" ) ;

// Main

/**
 * The user singleton collection of the application.
 */
users = 
{
    
} ;

/**
 * Invoked when the application is started.
 */
application.onAppStart = function()
{
    trace("application start") ;
}

/**
 * Invoked when the application is stopped.
 */
application.onAppStop = function()
{
    trace("application stop") ;
}

/**
 * Invoked when a new client is connected.
 */
application.onConnect = function( client , name )
{
    
    if ( config.referrers != null && config.referrers.length > 0 && Arrays.contains( config.referrers, client.referrer ) == false )
    {
        trace( "application reject : The client referrer isn't valid.") ;
        application.rejectConnection( client , { code : "rtmp_referrer_error" , message : "The client referrer isn't valid." } ) ;
    }
    else
    {
        if ( users[name] == null )
        {
            
            client.name = name ;
            
            var user /*UserVO*/ = new UserVO( name , client ) ;
            user.streamID   = "stream_" + (new Date().valueOf()) + "_" + name ;
            
            users[name] = user ;
            
            application.acceptConnection( client ) ;
            
            trace("application connect : " + name ) ;
            
            try
            {
                client.call( "createUser" , null , user , config.stratusKey  ) ;
            }
            catch( e /*Error*/ )
            {
                trace( "send stratus key failed with the user:'" + name + "', message:" + e.message ) ;
            }
        }
        else
        {
            application.rejectConnection( client , { code : "rtmp_user_already_register_error" , message : "A client is already register with the specified name:" + name } ) ;
        }
    }
}

/**
 * Invoked when a client is disconnected.
 */
application.onDisconnect = function( client )
{
    try
    {
        var name = client.name ;
        
        if ( users[name] != null )
        {
            trace("application disconnect : " + name ) ;
            delete users[name] ;
            
            var speaker = null ;
            try
            {
                speaker = client.speaker ;
                speaker = users[speaker] ;
                speaker.client.call( "closeSession" ) ;
            }
            catch( e /*Error*/ )
            {
                //
            }
        }
        else
        {
            // trace("application disconnect failed with a no register client in the 'users' collection." ) ;
        }
    }
    catch( e /*Error*/ )
    {
        trace("application disconnect failed : " + e.message ) ;
    }
}

/// client callback methods


Client.prototype.respondInvitation = function( to /*String*/ , peedID /*String*/ )
{
    try
    {
        var fromUser /*UserVO*/ = users[ this.name ] ;
        var toUser /*UserVO*/   = null ;
        
        trace( "respond invitation  from:" +  this.name + " to :" + to ) ;
        
        try
        {
            toUser = users[ to ] ;
        }
        catch( e /*Error*/ )
        {
            //
        }
        
        if ( toUser == null )
        {
            return false ;
        }
        else
        {
            toUser.client.speaker = fromUser.name ;
            toUser.client.call("finishInvitation", null, fromUser, peedID ) ;
            
            fromUser.client.speaker = toUser.name ;
            
            return true ;
        }
    }
    catch( e /*Error*/ )
    {
        trace( e ) ;
    }
}

Client.prototype.sendInvitation = function( ask /*Object*/ )
{
    try
    {
        
        var fromUser /*UserVO*/ = users[ this.name ] ;
        var toUser   /*UserVO*/ = users[ ask.to ] ;
        trace( "sendInvitation from:" + fromUser + " to:" +  ask.to + " peerID:" + ask.peerID   ) ;
        var responder = {} ;
        responder.onResult = function( result )
        {
            var hasGuest = (result === true) ;
            if ( hasGuest )
            {
                fromUser.client.call("buzzy", null, ask.to ) ;
            }
            else
            {
                toUser.client.call( "receiveInvitation", null , fromUser , ask.peerID ) ;
            }
        }
        if ( fromUser != null && toUser != null )
        {
            toUser.client.call( "hasGuest" , responder ) ;
            return true ;
        }
        else
        {
            return false ;
        }
    }
    catch( e /*Error*/ )
    {
        trace( e ) ;
    }
}